package net.techwatch.commons.backup;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.ResultSetDynaClass;
import org.apache.commons.dbutils.RowProcessor;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class BeanWriterHandler extends BeanHandler {

	private Log log = LogFactory.getLog(BeanWriterHandler.class);
	
	private BackupTool tool;
	
	public BeanWriterHandler(Class type, RowProcessor convert) {
		super(type, convert);
	}

	public BeanWriterHandler(Class type) {
		super(type);
	}

	public BeanWriterHandler(BackupTool tool) {
		super(null);
		this.tool = tool;
	}
	
	@Override
	public Object handle(ResultSet rs) throws SQLException {
		ResultSetDynaClass dynaClass = new ResultSetDynaClass(rs);
		tool.setDynaProperties(dynaClass.getDynaProperties());
		
		try {
			Iterator it = dynaClass.iterator();
			while(it.hasNext()) {
				DynaBean dBean = (DynaBean) it.next();
				tool.writeData(dBean);
			}
		} catch(IOException e) {
			log.error("Error while writing data", e);
			throw new SQLException();
		}
			
		return null;
	}

}
